package org.ykh.service.policy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.ykh.common.utils.HttpUtils;
import org.ykh.service.policy.RestrictPolicy;


import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Objects;

/**
 * @author ykh
 */

@Component
public class TimingRestrictPolicy implements RestrictPolicy {


    @Autowired
    private StringRedisTemplate redisTemplate;

    //单位时间内只能访问指定次数
    @Override
    public boolean isRestrict(HttpServletRequest request, String encoded, Duration interval, int threshold) {

        final String ip = HttpUtils.ip(request);
        String key = ip + ":" + encoded;
        final Boolean aBoolean = redisTemplate.hasKey(key);
        if (aBoolean != null && aBoolean) {
            return Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(key))) > threshold;
        }
        return false;

    }

    @Override
    public void restrictPolicy(HttpServletRequest request, String encoded, Duration interval, int threshold) {
        final String ip = HttpUtils.ip(request);
        String key = ip + ":" + encoded;
        final ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.setIfAbsent(key,"1",interval);
        opsForValue.increment(key);
    }
}
